<?php
namespace api\know\model;

use api\know\model\KnowBaseModel;
use think\facade\Log;

class ChapterModel extends KnowBaseModel
{
    /**
     * 模型名称
     * @var string
     */
    protected $name = 'know_chapter';
	public static $QueryField = ['id', 'uuid', 'name', 'order_number', 'level', 'parent_uuid'];

	public function getChapterTree($relate_uuid) 
	{
		$rows = $this->where(['relate_uuid' => $relate_uuid, 'is_delete' => 0])
					->field(ChapterModel::$QueryField)
					->select()
					->toArray();

		$cache = [];
		// 排序
		array_multisort(array_column($rows, 'order_number'), SORT_ASC, $rows);
		array_multisort(array_column($rows, 'level'), SORT_DESC, $rows);
		
		// 初始化树形
		foreach ($rows as &$value) 
		{
			$value['name'] = htmlspecialchars_decode($value['name']);;
			$value['children'] = [];
			$cache[$value['uuid']] = $value;
		}

		foreach ($cache as &$v)
		{
			if (empty($v['parent_uuid'])) 
			{
				continue;
			}
			else
			{
				$parent = $cache[$v['parent_uuid']];
				if (!empty($parent))
				{
					Log::debug('--存在父级节点--' . $parent['name'] . '----' . $v['name']);
					array_push($cache[$v['parent_uuid']]['children'], $v);
				}
				else
				{
					Log::debug('-------xxxxxxxx------' . $v['name']);
					continue;
				}
			}
		}

		$tree = array_values(array_filter($cache, function ($var) {
			return $var['level'] == 1;
		}));
		return $tree;
	}
	
}